from django.shortcuts import render

# Create your views here.
from django.views import View
from apps.users.models import User
from django.http import JsonResponse
import re
class UsernameCountView(View):
    def get(self,request,username):
        # # 1.接收参数
        # if not re.match(r'^[a-zA-Z0-9]{5,20}$',username):
        #     return JsonResponse({'code':200,'errmsg':'用户名不满足需求'})
        # # 2.校验参数
        count=User.objects.filter(username=username).count()
        return JsonResponse({'code':0,'count':count,'errmsg':'ok'})
import json
class RegisterView(View):
    def post(self,request):
        # 1.接收请求
        body_bytes=request.body
        body_str=body_bytes.decode()
        body_dict=json.loads(body_str)
        #2.获取数据
        username=body_dict.get('username')
        password=body_dict.get('password')
        password2=body_dict.get('password2')
        mobile=body_dict.get('mobile')
        allow=body_dict.get('allow')
        # 3.校验数据
        #3.1 校验参数是否齐全
        if not all([username,password,password2,mobile,allow]):
            return JsonResponse({'code':400,'errmsg':'参数不足'})
        #3.2 校验用户名
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return JsonResponse({'code':400,'errmsg':'用户名不满足需求'})
        if not re.match(r'^[a-zA-Z0-9]{8,20}$',password):
            return JsonResponse({'code':400,'errmsg':'密码不满足需求'})
        if password!=password2:
            return JsonResponse({'code':400,'errmsg':'两次密码不一致'})
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'code':400,'errmsg':'手机号不满足需求'})
        if allow!=True:
            return JsonResponse({'code':400,'errmsg':'请同意协议'})
        # 3.3 校验用户名是否重复
        try:
            user=User.objects.get(username=username)
        except User.DoesNotExist:
            user=None
        if user:
            return JsonResponse({'code':400,'errmsg':'用户名重复'})
        # 3.4 校验手机号是否重复
        try:
            user=User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user=None
        if user:
            return JsonResponse({'code':400,'errmsg':'手机号重复'})
        # 4.保存数据到数据库
        # user=User(username=username,password=password,mobile=mobile)
        # user.save()
        #4.保存数据到数据库方法2，密码加密
        user=User.objects.create_user(username=username,password=password,mobile=mobile)
        #登录状态保持
        from django.contrib.auth import login
        login(request,user)
        return JsonResponse({'code':0,'errmsg':'ok'})
class Ceshi(View):
    def get(self,request):
        return JsonResponse({'code':0,'errmsg':'ok!!!!'})
class LoginView(View):
    def post(self,request):
        data=json.loads(request.body.decode())#1获取数据
        username=data.get('username')
        password=data.get('password')
        remembered=data.get('remembered')
        # 2校验数据
        if not all([username,password]):
            return JsonResponse({'code':400,'errmsg':'参数不足'})
        #2.2判断用户名是手机号还是用户名
        if re.match('1[3-9]\d{9}',username):
            User.USERNAME_FIELD='mobile'
        else:
            User.USERNAME_FIELD='username'
        # 3.用户名密码校验是否正确
        from django.contrib.auth import authenticate
        user=authenticate(username=username,password=password)
        if user is None:
            return JsonResponse({'code':400,'errmsg':'用户名或密码错误'})
        # 4.状态保持session
        from django.contrib.auth import login
        login(request,user)
        # 5.设置session的过期时间
        if remembered:
            request.session.set_expiry(None)#None表示默认两周
        else:
            request.session.set_expiry(0)#0表示关闭浏览器就过期
        #6.返回响应
        response=JsonResponse({'code':0,'errmsg':'ok'})
        response.set_cookie('username',user.username,max_age=3600*24*14)
        return response
class LogoutView(View):
    def delete(self,request):
        from django.contrib.auth import logout
        logout(request)#删除session
        response=JsonResponse({'code':0,'errmsg':'ok'})
        response.delete_cookie('username')#删除cookie
        return response

#用户中心，必须是登录用户才可以访问
# 导入LoginRequiredMixin作用是登录用户才可以访问，但未登录访问会重定向，并不是json格式的
#我们需要的是json数据,所以需要重写LoginRequiredMixi里的方法为LoginRequiredJSONMixin
from utils.views import LoginRequiredJSONMixin
class CenterView(LoginRequiredJSONMixin,View):
    def get(self,request):
        #1.获取用户信息
        info_data={
            'username':request.user.username,
            'mobile':request.user.mobile,
            'email':request.user.email,
            'email_active':request.user.email_active,
        }
        #2.返回响应
        return JsonResponse({'code':0,'errmsg':'ok','info_data':info_data})
from itsdangerous import TimedJSONWebSignatureSerializer
from meiduo_mall import settings
s = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,expires_in=3600)
token=s.dumps({'username':'zhangsan'})#加密
print(token)
s.loads(token)#解密
class EmailView(LoginRequiredJSONMixin,View):
    def put(self,request):
        data=json.loads(request.body.decode())#1获取数据
        email=data.get('email')
        #2校验数据
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',email):
            return JsonResponse({'code':400,'errmsg':'邮箱格式错误'})
        #3.保存邮箱到数据库
        request.user.email=email#request.user就是登录用户的实例对象，对应数据模型中的User,必须在类的参数继承LoginRequiredJSONMixin
        request.user.save()
        # 4.发送邮件
        from django.core.mail import send_mail
        subject = '美多商城邮箱验证'  # 标题
        message = "" # 内容
        #4.1对a标签的激活链接进行加密处理
        from apps.users.utils import generic_email_verify_token
        token=generic_email_verify_token(request.user.id)
        verify_url=f'http://www.meiduo.site:8080/success_verify_email.html?token={token}'
        #4.2拼接激活链接
        html_message = f"<p>您的邮箱是{email}</p>激活链接<a href={verify_url}>{verify_url}</a>" # html格式的邮件内容
        from_email = '美多商城<mufahe5@163.com>'  # 发件人
        recipient_list = [email,'mufahe5@163.com'] # 收件人列表
        fail_silently = False  # 是否失败不报错
        send_mail(
            subject=subject,
            message=message,
            html_message=html_message,
            from_email=from_email,
            recipient_list=recipient_list,
            fail_silently=fail_silently,
        )
        return JsonResponse({'code': 0, 'errmsg': 'ok'})
class EmailVerifyView(View):
    def put(self,request):
        params=request.GET#1请求参数
        token=params.get('token')#2获取参数
        if not token:#3验证参数
            return JsonResponse({'code':400,'errmsg':'缺少token'})
        #4获取user_id
        from apps.users.utils import check_verify_token#解密
        user_id=check_verify_token(token)
        if not user_id:
            return JsonResponse({'code':400,'errmsg':'token无效'})
        #5根据user_id查询数据
        user=User.objects.get(id=user_id)
        #6修改数据
        user.email_active=True
        user.save()
        # 7返回响应JSON
        return JsonResponse({'code':0,'errmsg':'ok'})